package com.accompany.main;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.accompany.R;
import com.accompany.adapter.BaseRecyclerHolder;
import com.accompany.adapter.BaseRecyclerRefreshAdapter;
import com.accompany.api.bean.VersionBean;
import com.accompany.api.category.VersionCategory;
import com.accompany.api.presenter.VersionMsgPresenter;
import com.accompany.base.BaseActivity;
import com.accompany.dialog.CheckedUpdateVersionData;
import com.accompany.dialog.LoginOutDialog;
import com.accompany.dialog.VersionDialog;
import com.accompany.fragment.home.HomeFragment;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.fragment.my.MyFragment;
import com.accompany.fragment.order.OrderFragment;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;
import com.accompany.view.RecyclerViewLayoutManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;

public class MainActivity extends BaseActivity implements VersionCategory.View {
    private long exitTime = 0;
    @BindView(R.id.bottom_main)
    BottomNavigationView bottomMain;
    private MyFragment myFragment;
    private OrderFragment orderFragment;
    private HomeFragment homeFragment;
    private Fragment[] fragments;
    private int lastfragment = 0;
    private VersionMsgPresenter mPresener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initLayoutView() {
        YCAppBar.setStatusBarColor(MainActivity.this,
                ContextCompat.getColor(MainActivity.this,
                        R.color.base_color));
        initLayout();
    }

    private void initLayout() {
        mPresener = new VersionMsgPresenter(this);
        SetPersenter(mPresener);
        homeFragment = new HomeFragment();
        orderFragment = new OrderFragment();
        myFragment = new MyFragment();
        updateVersion();
        fragments = new Fragment[]{homeFragment, orderFragment, myFragment};
        //设置fragment到布局
        getSupportFragmentManager().beginTransaction().replace(R.id.contentContainer, homeFragment).show(homeFragment).commit();
        //这里是bottomnavigationview的点击事件
        bottomMain.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private void updateVersion() {
        String oldVersionName = null;
        try {
            oldVersionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mPresener.getVersionMsg();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.home:
                    //这里因为需要对3个fragment进行切换
                    //start
                    if (lastfragment != 0) {
                        switchFragment(lastfragment, 0);
                        lastfragment = 0;
                    }
                    //设置状态栏为黑色
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.base_color));
                    //如果只是想测试按钮点击，不管fragment的切换，可以把start到end里面的内容去掉
                    return true;
                case R.id.order:
                    if (lastfragment != 1) {
                        switchFragment(lastfragment, 1);
                        lastfragment = 1;
                    }
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.base_color));
                    return true;
                case R.id.my:
                    if (lastfragment != 2) {
                        switchFragment(lastfragment, 2);
                        lastfragment = 2;
                    }
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.base_color));
                    return true;
                default:
                    break;
            }
            return false;
        }
    };

    /**
     * 切换fragment
     */
    private void switchFragment(int lastfragment, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //隐藏上个Fragment
        transaction.hide(fragments[lastfragment]);
        if (fragments[index].isAdded() == false) {
            transaction.add(R.id.contentContainer, fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToastERROR(MainActivity.this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                BaseApplication.removeALLActivity();
                System.exit(0);
            }
            return true;
        }
        return false;
    }

    /**
     * 版本更新
     *
     * @param versionBean
     */
    @Override
    public void getVersionMsg(VersionBean versionBean) {
        if (versionBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (versionBean.getData() != null) {
                if (isUpdateForVersion(versionBean.getData().getVersionCode(), getCurrentVersion(MainActivity.this))) {
                    String str = versionBean.getData().getUpdateLog();
                    String[] split = str.split("\\#");
                    List<String> mlist = Arrays.asList(split);
                    VersionDialog dialog = new VersionDialog(MainActivity.this);
                    dialog.show();
                    TextView vers_number = (TextView) dialog.findViewById(R.id.vers_number);
                    vers_number.setText(versionBean.getData().getVersionCode());
                    RecyclerView mRecyclerView = (RecyclerView) dialog.findViewById(R.id.recycler_version);
                    RecyclerViewLayoutManager.setLinearVerticalManager(MainActivity.this, mRecyclerView);
                    mRecyclerView.setAdapter(new BaseRecyclerRefreshAdapter<String>(MainActivity.this, mlist, R.layout.item_version_view) {
                        @Override
                        public void convert(BaseRecyclerHolder holder, String item, int position, boolean isScrolling) throws IOException {
                            holder.setText(R.id.version_nmae, item);
                        }
                    });
                    dialog.findViewById(R.id.submit_update).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CheckedUpdateVersionData checkedUpData = new CheckedUpdateVersionData();
                            checkedUpData.updata(MainActivity.this, versionBean.getData().getDownloadUrl());
                            dialog.dismiss();
                        }
                    });
                    dialog.findViewById(R.id.icon_delete).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        }
        else if (versionBean.getCode()==ConstantStaticUrl.NO_LOGIN_CODE){
            LoginOutDialog dialog =  LoginOutDialog.getLoginOutDialog(MainActivity.this);
            dialog.show();
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();

                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(MainActivity.this);
                    finish();
                    dialog.dismiss();

                }
            });
        }else {
            ToastUtil.showToastINFO(MainActivity.this,versionBean.getMsg());
        }
    }


    public static boolean isUpdateForVersion(String newVersion, String indexVersion) {
        // boolean resultFlag = false;

        if ("".equals(newVersion) || null == newVersion
                || "null".equals(newVersion)) {
            return false;
        } else {

            String[] newNums = newVersion.substring(1, newVersion.length()).split("\\.");
            String[] indexNums = indexVersion.split("\\.");

            if (newNums.length > indexNums.length) {// 服务器版本长度 比当前版本要长
                for (int i = 0; i < newNums.length; i++) {
                    //位数不够,给当前版本补零
                    int currentValue = 0;
                    if (i < indexNums.length) {
                        currentValue = Integer.parseInt(indexNums[i]);
                    }
                    // 服务器上同位版本数如果有一个数大于 当前的，就是最新版，要更新；否则不更新
                    if (Integer.parseInt(newNums[i]) > currentValue) {
                        return true;
                    } else if (Integer.parseInt(newNums[i]) <= currentValue) {
                        return false;
                    }
                }
                return false;
            } else if (newNums.length <= indexNums.length) {
                for (int i = 0; i < indexNums.length; i++) {
                    //位数不够,给服务器版本补零
                    int newValue = 0;
                    if (i < newNums.length) {
                        newValue = Integer.parseInt(newNums[i]);
                    }
                    // 服务器上同位版本数如果有一个数大于 当前的，就是最新版，要更新；否则不更新
                    if (newValue > Integer.parseInt(indexNums[i])) {
                        return true;
                    } else if (newValue <= Integer.parseInt(indexNums[i])) {
//                        return false;
                    }
                }
                return false;
            }
        }
        return false;
    }
    // 获取当前版本的版本号
    public static String getCurrentVersion(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.
                    getPackageName(), 0);
            Log.d("TAG", "getCurrentVersion: 版本值--》" + packageInfo.versionCode);
            Log.d("TAG", "getCurrentVersion: 版本号--》" + packageInfo.versionName);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public void SetPersenter(Object persenter) {

    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {

    }
}
